package com.apinji.alipay;

import com.apinji.alipay.dto.AlipayConsumeDto;
import com.apinji.alipay.dto.AlipayConsumeQueryDto;
import com.apinji.alipay.service.AlipayPayService;
import com.apinji.common.domain.wrapper.Reply;
import com.apinji.common.plugin.Mutual;
import com.apinji.common.plugin.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支付宝网站支付，支付
 *
 */
@RestController
@EnableAutoConfiguration
@EnableAsync
@RequestMapping("/v1.0/alipay")
public class AlipayPayController {
    @Autowired
    private AlipayPayService alipayPayService;

    /**
     * 支付宝网站支付
     *
     * @param alipayConsumeDto
     * @return
     */
    @RequestMapping(value = "/consume")
    @ResponseBody
    public Object consume(HttpServletRequest request, HttpServletResponse response, @RequestBody AlipayConsumeDto alipayConsumeDto) throws Exception{
        if(StrUtils.isEmpty(alipayConsumeDto.getUserUUID())) {
            return Mutual.invalidParam("无效参数[userUUID]").toString();
        }
        if(StrUtils.isEmpty(alipayConsumeDto.getOrderId())) {
            return Mutual.invalidParam("无效参数[orderId]").toString();
        }
        if(StrUtils.isEmpty(alipayConsumeDto.getOutOrderId())) {
            return Mutual.invalidParam("无效参数[outOrderId]").toString();
        }
        if(alipayConsumeDto.getTxnAmt() <= 0) {
            return Mutual.invalidParam("支付金额不能少于0").toString();
        }
        if(StrUtils.isEmpty(alipayConsumeDto.getOrderName())) {
            return Mutual.invalidParam("无效参数[orderName]").toString();
        }
        //
        return alipayPayService.consume(alipayConsumeDto, response, request);
    }

    /**
     * 交易状态查询
     * @param alipayConsumeQueryDto
     * @return
     */
    @RequestMapping(value = "/consumeQuery")
    public Reply consumeQuery(@RequestBody AlipayConsumeQueryDto alipayConsumeQueryDto){
        if(StrUtils.isEmpty(alipayConsumeQueryDto.getUserUUID())) {
            return Mutual.invalidParam("参数错误[userUUID]");
        }
        if(StrUtils.isEmpty(alipayConsumeQueryDto.getId())) {
            return Mutual.invalidParam("参数错误[id]");
        }
        return alipayPayService.consumeQuery(alipayConsumeQueryDto);
    }


    @RequestMapping(value = "/backNotify")
    public void backRcvResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
        alipayPayService.backNotify(request, response);
    }





    //----------------------------测试
    @RequestMapping(value = "/returnUrl")
    @ResponseBody
    public String callBackReturnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return alipayPayService.returnUrl(request, response);
    }
}
